package com.kvest.scanrecognizer.core;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import com.kvest.scanrecognizer.utility.FileUtility;

import java.io.File;

/**
 * Created with IntelliJ IDEA.
 * User: Kvest
 * Date: 13.09.13
 * Time: 22:59
 * To change this template use File | Settings | File Templates.
 */
public class Settings {
    private static final String SHARED_PREFERENCES_NAME = "com.kvest.scanrecognizer.core.Settings.SETTINGS";
    private static final String WORKING_DIR_KEY = "working_dir";
    private static final String DEFAULT_WORKING_DIRECTORY = "/Photo to text";
    private String workingDirectory;

    private static Settings instance;
    private static final Object lock = new Object();

    public static Settings getInstance(Context context) {
        synchronized (lock) {
            if (instance == null) {
                instance = new Settings(context);
            }
        }

        return instance;
    }

    private Settings(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
        workingDirectory = sharedPreferences.getString(WORKING_DIR_KEY, DEFAULT_WORKING_DIRECTORY);
    }

    public void save(Context context) {
        SharedPreferences.Editor editor = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).edit();
        try {
            editor.putString(WORKING_DIR_KEY, workingDirectory);
        } finally {
            editor.commit();
        }
    }

    public String getShortWorkingDirectory() {
        return workingDirectory;
    }

    public void setWorkingDirectory(String value) {
        workingDirectory = value;
    }

    public String getWorkingDirectory() {
        //Create if not exists
        FileUtility.createDirIfNotExists(workingDirectory);

        String fullWorkingDirectory = Environment.getExternalStorageDirectory().getPath() + workingDirectory + File.separator;

        return fullWorkingDirectory;
    }
}
